<?php
declare (strict_types=1);

namespace app\listener;

use think\facade\Db;

class ChangeLayerProductNum
{
    /**
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($event)
    {
        $cupboardId = $event['cupboard_id'];
        $num = $event['num'];
        $groupId = Db::connect('cupboard')->table('cupboard')->where('id', $cupboardId)->value('group_id');
        if (!$groupId) {
            return;
        }
        $productArr = Db::connect('cupboard')->table('layer_product')->where('group_id', $groupId)->column('product_id');
        if (!$productArr) {
            return;
        }
        if (count($productArr) > 2) {
            return;
        }
        if (count($productArr) == 2) {
            $productId1 = $productArr[0];
            $num1 = intval($num / 2);
            $productId2 = $productArr[1];
            $num2 = $num - $num1;
            Db::connect('cupboard')->table('cupboard_layer_product')
                ->where('cupboard_id', $cupboardId)
                ->where('product_id', $productId1)
                ->save([
                    'num' => $num1,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            Db::connect('cupboard')->table('cupboard_layer_product')
                ->where('cupboard_id', $cupboardId)
                ->where('product_id', $productId2)
                ->save([
                    'num' => $num2,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
        } else {
            $productId = $productArr[0];
            Db::connect('cupboard')->table('cupboard_layer_product')
                ->where('cupboard_id', $cupboardId)
                ->where('product_id', $productId)
                ->save([
                    'num' => $num,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
        }
    }
}
